package com.yuanye.yeecho.base;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.yuanye.yeecho.utils.WifiUtil;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseActivity extends AppCompatActivity {

    private static final String TAG = "BaseActivity";

    private Context context;
    private PermissionCallback permissionCallback;
    private String[] permissions;
    protected WifiUtil wifiUtil;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        context = this;
        wifiUtil = WifiUtil.getInstance(this);
    }

    protected void showWarningDialog(final String content){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Dialog dialog = new AlertDialog.Builder(context)
                        .setMessage(content)
                        .setPositiveButton("确定", null)
                        .create();
                dialog.show();
            }
        });
    }

    protected void toast(final String content){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
            }
        });
    }


    protected void checkPermissions(String[] permissions, PermissionCallback callback) {
        this.permissionCallback = callback;
        this.permissions = permissions;
        //动态权限申请
//        String[] permissions = {
//                Manifest.permission.ACCESS_FINE_LOCATION,
//                Manifest.permission.ACCESS_COARSE_LOCATION,
//                Manifest.permission.READ_EXTERNAL_STORAGE,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.RECORD_AUDIO
//        };
        //统计是否有权限未赋予
        List<String> missingPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add(permission);
            }
        }
        if (!missingPermissions.isEmpty()) {
            Log.d(TAG, "有权限未赋予,个数:"+missingPermissions.size());
            //检查是否有权限被永久拒绝
            boolean shouldShowDialog = false;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                for (String permission: missingPermissions){
                    if (shouldShowRequestPermissionRationale(permission)){
                        shouldShowDialog = true;
                        break;
                    }
                }
            }
            if (shouldShowDialog){
                Dialog dialog = new AlertDialog.Builder(context)
                        .setMessage("请跳转到设置界面手动赋予权限，否则无法测试！")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //有权限被永久拒绝，跳转到设置界面
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivityForResult(intent, 9999);
                            }
                        })
                        .create();
                dialog.show();

            }else{
                //发起权限申请
                ActivityCompat.requestPermissions(this,
                        missingPermissions.toArray(new String[0]),
                        9999);
            }

        }else{
            Log.d(TAG, "所有权限都已经被授予");
            if (permissionCallback != null) permissionCallback.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "requestCode:"+requestCode+" len:"+grantResults.length);
        if (requestCode == 9999) {
            boolean isAllGranted = true;
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    // 权限被拒绝
                    isAllGranted = false;
                    break;
                }
            }
            if (isAllGranted){
                permissionCallback.onGranted();
            }else{
                permissionCallback.onFail();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 9999){
            checkPermissions(permissions, permissionCallback);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected interface PermissionCallback{
        void onGranted();
        void onFail();
    }

}
